$(function () {
    let buttonGroup = [
        {
            id: 'btn_cancel_filter',
            size: 'small',
            text: '清除过滤',
            iconCls: 'icon-clear',
            plain: true,
            onClick: btn_cancel_filter
        },
        {
            id: 'btn_export',
            size: 'small',
            text: '导出Excel',
            iconCls: 'icon-page_excel',
            plain: true,
            onClick: btn_export_excel
        },
        {
            id: 'btn_grid_columns',
            size: 'small',
            text: '列',
            iconCls: 'icon-text_columns',
            plain: true,
            onClick: btn_open_column_list
        },
        {
            id: 'btn_close', size: 'small', text: '关闭', iconCls: 'icon-no', onClick: btn_close,
            plain: true
        },
    ];
    buttonGen($('#north'), buttonGroup);
    bindEnterEvents();
})
const materialColumns = [
    {title: 'id', field: 'id', hidden: true,},
    {title: '制单日期', field: 'orderDate', editor: {type: 'datebox', options: {value: getCurrentDate()}}},
    {
        title: '单据类型', field: 'billType', editor: {
            type: 'combobox', options: {
                url: 'billType/listQuery',
                queryParams: {storageId: 1},
                method: 'GET',
                textField: 'billTypeName', valueField: 'id',
                limitToList: true,
                panelHeight: 200,
                required: true
            }
        }
    },
    {
        title: '供应商', field: 'supplierId', editor: {
            type: 'combobox', options: {
                url: 'supplier/listQuery',
                method: 'GET',
                textField: 'supplierName', valueField: 'id',
                limitToList: true,
                panelHeight: 200,
                required: true
            }
        }
    },
    {title: '单据编号', field: 'orderCode', editor: {type: 'textbox', options: {required: false, readonly: true}}},
    {title: '批次号', field: 'batchNum', editor: {type: 'textbox', options: {required: true}}},
    {
        title: '原料规格', field: 'materialSpec', editor: {
            type: 'combobox', options: {
                url: 'specification/listQuery',
                method: 'GET',
                textField: 'specName',
                valueField: 'specName',
                panelHeight: 200,
                required: true,
            }
        }
    },
    {title: '箱数', field: 'boxAmount', editor: {type: 'numberbox', options: {precision: 1, required: true}}},
    {title: '入库匹数', field: 'inputAmount', editor: {type: 'numberbox', options: {precision: 0, required: true}}},
    {title: '金额', field: 'inputMoney', editor: {type: 'numberbox', options: {precision: 2, required: true}}},
    {title: '备注', field: 'remarks', editor: {type: 'textbox', options: {required: false}}},
    {
        title: '制单人',
        field: 'createUserId',
        editor: {
            type: 'combobox',
            options: {
                readonly: true,
                url: 'sysUser/query',
                method: 'GET',
                textField: 'userName',
                valueField: 'id',
                limitToList: true
            }
        }
    },
];

//  选中事件
function onSelect(title, index) {
    switch (index) {
        case 0:
            if ($('#v_grid_3').data('kendoGrid') == undefined) {
                grid_4();
            }
            break;
        case 1:
            if ($('#v_grid_4').data('kendoGrid') == undefined) {
                grid_5();
            }
            break;
    }
}

//  收货管理 - 应收应付 - 已收款
function grid_4() {
    let SUFFIX = "_d";
    let client = new kendo.data.DataSource({data: []});
    let address = new kendo.data.DataSource({data: []});
    let specification = new kendo.data.DataSource({data: []});
    let dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "delivery/report/fhdtl",
                dataType: "json",
                type: "GET",
                data: {
                    start: $('#start').datebox('getValue'),
                    end: $('#end').datebox('getValue'),
                    // textField: $('#column').combobox('getValue'),
                    // valueField: $('#value').textbox('getValue'),
                }
            }
        },
        schema: {
            model: {
                id: 'id',
                fields: {
                    ps: {type: "number"},
                    qty: {type: "number"},
                    money: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "ps", aggregate: "sum"},
            {field: "qty", aggregate: "sum"},
            {field: "money", aggregate: "sum"},
        ],
        change: function (e) {
            let data = this.data();
            client.data(unique(data, 'client'));
            address.data(unique(data, 'address'));
            specification.data(unique(data, 'pmgg'));
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })
            // $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })
            // $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        }
    });
    let columns = [
        {field: "no", title: "序号", filterable: false, template: "<span class='row_number'></span>", width: 40},
        {
            field: "id",
            title: '编号',
            width: 93,
            hidden: true,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
        },
        {
            field: "client",
            title: '项目',
            width: 93,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
            filterable: {multi: true, search: true, dataSource: client}
        },
        {
            field: "ps",
            title: '匹数',
            width: 93,
            template: item => item['ps'] ? parseFloat(item['ps']).toFixed(1) : '',
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:right;'},
            filterable: {multi: true, search: true}
        },
        {
            field: "qty",
            title: '重量',
            width: 93,
            template: item => item['qty'] ? parseFloat(item['qty']).toFixed(1) : '',
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:right;'},
            filterable: {multi: true, search: true}
        },
        {
            field: "price",
            title: '入库金额',
            width: 93,
            template: item => item['price'] ? parseFloat(item['price']).toFixed(2) : '',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:right;'},
            filterable: {multi: true, search: true}
        },
        {
            field: "money",
            title: '金额',
            width: 93,
            template: item => item['money'] ? parseFloat(item['money']).toFixed(2) : '',
            footerAttributes: {style: 'text-align:right;'},
            footerTemplate: '#=kendo.format("{0:n2}",sum)#',
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:right;'},
            filterable: {multi: true, search: true}
        },
        {
            field: "b_data",
            title: '发货时间',
            width: 85,
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            filterable: {multi: true, search: true}
        },
    ];
    let grid = $("#v_grid_3").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "原料序时表.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });
        },
        columnHide: function (e) {
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
        },
        columnShow: function (e) {
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null, SUFFIX);
        },
        columnResize: function (e) {
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null, SUFFIX);
            }
        },
        columnReorder: function (e) {
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field']
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_grid_3').data('kendoGrid');
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    grid01.setOptions({
        columns: columns
    });
    /*$('body').on('mouseenter', 'th', function (e) {
        $('.k-grid-filter').finish();
        $(this).find('.k-grid-filter').fadeIn();
    })
    $('body').on('mouseleave', 'th', function (e) {
        $(this).find('.k-grid-filter').fadeOut();
    })*/
}

//  收货管理 - 应收应付 - 应付款
function grid_5() {
    let SUFFIX = "_e";
    let client = new kendo.data.DataSource({data: []});
    let billtype = new kendo.data.DataSource({data: []});
    let collectiontype = new kendo.data.DataSource({data: []});
    let billmemo = new kendo.data.DataSource({data: []});
    let dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "delivery/report/received",
                dataType: "json",
                type: "GET",
                data: {
                    start: $('#start').datebox('getValue'),
                    end: $('#end').datebox('getValue'),
                    // textField: $('#column').combobox('getValue'),
                    // valueField: $('#value').textbox('getValue'),
                }
            }
        },
        schema: {
            model: {
                id: 'id',
                fields: {
                    money: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "money", aggregate: "sum"},
        ],
        change: function (e) {
            let data = this.data();
            client.data(unique(data, 'client'));
            address.data(unique(data, 'address'));
            specification.data(unique(data, 'pmgg'));
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })
            // $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })
            // $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        }
    });
    let columns = [
        {field: "no", title: "序号", filterable: false, template: "<span class='row_number'></span>", width: 40},
        {
            field: "id",
            title: '编号',
            width: 93,
            hidden: true,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
        },
        {
            field: "client",
            title: '客户',
            width: 93,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
            filterable: {multi: true, search: true, dataSource: client}
        },
        {
            field: "billtype",
            title: '单据类型',
            width: 93,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
            filterable: {multi: true, search: true, dataSource: billtype}
        },
        {
            field: "collectiontype",
            title: '收款类型',
            width: 93,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
            filterable: {multi: true, search: true, dataSource: collectiontype}
        },
        {
            field: "money",
            title: '金额',
            width: 93,
            template: item => item['money'] ? parseFloat(item['money']).toFixed(2) : '',
            footerAttributes: {style: 'text-align:right;'},
            footerTemplate: '#=kendo.format("{0:n2}",sum)#',
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:right;'},
            filterable: {multi: true, search: true}
        },
        {
            field: "billdate",
            title: '日期',
            width: 85,
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            filterable: {multi: true, search: true}
        },
        {
            field: "billmemo",
            title: '备注',
            width: 93,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
            filterable: {multi: true, search: true, dataSource: billmemo}
        },
    ];
    let grid = $("#v_grid_4").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "已收款序时表.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });
        },
        columnHide: function (e) {
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
        },
        columnShow: function (e) {
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null, SUFFIX);
        },
        columnResize: function (e) {
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null, SUFFIX);
            }
        },
        columnReorder: function (e) {
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field']
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_grid_4').data('kendoGrid');
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    grid01.setOptions({
        columns: columns
    });
   /* $('body').on('mouseenter', 'th', function (e) {
        $('.k-grid-filter').finish();
        $(this).find('.k-grid-filter').fadeIn();
    })
    $('body').on('mouseleave', 'th', function (e) {
        $(this).find('.k-grid-filter').fadeOut();
    })*/
}

function btn_cancel_filter() {
    switch (getCurrentIndex()) {
        case 0:
            $('#v_grid_3').data('kendoGrid').dataSource.filter({});
            break;
        case 1:
            $('#v_grid_4').data('kendoGrid').dataSource.filter({});
            break;
    }
}

function btn_search() {
    switch (getCurrentIndex()) {
        case 0:
            $('#v_grid_3').data('kendoGrid').dataSource.read({
                start: $('#start').datebox('getValue'),
                end: $('#end').datebox('getValue'),
                // textField: $('#column').combobox('getValue'),
                // valueField: $('#value').textbox('getValue'),
            })
            break;
        case 1:
            $('#v_grid_4').data('kendoGrid').dataSource.read({
                start: $('#start').datebox('getValue'),
                end: $('#end').datebox('getValue'),
                // textField: $('#column').combobox('getValue'),
                // valueField: $('#value').textbox('getValue'),
            })
            break;
    }
}

function btn_add() {
    openDialog({});
    $.formDialog.enableBtn(['保存', '关闭']);
}

function openDialog(loadData) {
    $.formDialog.open({
        columns: materialColumns,
        loadData: loadData,
        mode: '原料入库',
        width: 381,
        height: 485,
        buttons: [],
        toolbar: [
            {
                text: '新增', iconCls: 'icon-add', handler: e => {
                    $('.form-dialog-edit').eq(0).dialog('panel').find('form').form('clear');
                    $.formDialog.enableBtn(['保存', '关闭']);
                    $.formDialog.enableEditing();
                }
            },
            {
                text: '修改', iconCls: 'icon-edit', handler: e => {
                    $.formDialog.enableBtn(['保存', '关闭']);
                    $.formDialog.enableEditing();
                }
            },
            {
                text: '保存', iconCls: 'icon-save', handler: e => {
                    let url = '';
                    let formData = $('.form-dialog-edit').eq(0).dialog('panel').find('form').serializeObject();
                    if (formData['id']) {
                        url = 'materialOrder/updateSelective';
                    } else {
                        url = 'materialOrder/insertSelective';
                    }
                    $('.form-dialog-edit').eq(0).dialog('panel').find('form').form('submit', {
                        url: url,
                        success: function (data) {
                            data = eval(`(${data})`);
                            if (data.success) {
                                $.formDialog.disableBtn(['保存']);
                                $.formDialog.disableEditing();
                                $('.form-dialog-edit').eq(0).dialog('panel').find('form').form('load', data.data);
                                btn_search();
                                $.messager.show({title: '提示', msg: data.message});
                            } else {
                                $.messager.alert('提示', data.message, 'error');
                            }
                        }
                    });
                }
            },
            {
                text: '复制', iconCls: 'icon-page_copy', handler: e => {
                    $('.form-dialog-edit').eq(0).dialog('panel').find('form').form('load', {
                        id: null
                    });
                    $.formDialog.enableEditing();
                    $.formDialog.enableBtn(['保存', '关闭']);
                }
            },
            {
                text: '作废', iconCls: 'icon-cancel', handler: e => {
                    $.messager.confirm('提示', '是否作废？', function (r) {
                        if (r) {
                            let formData = $('.form-dialog-edit').find('form').serializeObject();
                            if (!formData['id']) {
                                $.messager.alert('提示', '单据未保存!', 'warning');
                                return;
                            }
                            $.ajax({
                                url: 'materialOrder/cancelByPk',
                                data: {id: formData.id},
                                type: 'POST',
                                dataType: 'json',
                                success: function (data) {
                                    if (data.success) {
                                        $.formDialog.close();
                                        btn_search();
                                        $.messager.show({title: '提示', msg: data.message});
                                    } else {
                                        $.messager.alert('提示', data.message, 'error');
                                    }
                                }
                            });
                        }
                    })
                }
            },
            {
                text: '关闭', iconCls: 'icon-no', handler: e => {
                    $('.form-dialog-edit').eq(0).dialog('close');
                }
            }]
    })
}

function getCurrentIndex() {
    let tab = $('#tabs').tabs('getSelected');
    let index = $('#tabs').tabs('getTabIndex', tab);
    return index;
}

function btn_open_column_list() {
    let kendoGridID = '';
    switch (getCurrentIndex()) {
        case 0:
            kendoGridID = '#v_grid_3';
            break;
        case 1:
            kendoGridID = '#v_grid_4';
            break;
    }
    let options = $(kendoGridID).data('kendoGrid').getOptions().columns;
    if ($('#btn_open_column_list').length <= 0) {
        let div = $(`<div data-options="resizable:true,iconCls:'icon-text_columns',width:200,height:300,modal:true,title:'列'" 
                          class="easyui-dialog" id="btn_open_column_list">
                   </div>`);
        let form = $('<form style="width: 100%;height: 100%;"></form>')
        for (let i of options) {
            if (i.field) {
                let checkbox = $(`<div style="width: 100%;height: auto;padding: 5px;">
                <input class="easyui-checkbox" name="${i.field}" data-options="label:'${i.title}',
                labelWidth:120,value:true,name:'${i.field}'">
                </div>`);
                form.append(checkbox);
            }
        }
        let container = $(`<div></div>`);
        form.appendTo(div);
        div.appendTo(container);
        $('body').append(container);
        $.parser.parse($('#btn_open_column_list').parent());
        let formData = {};
        options.map(item => {
            formData[item['field']] = item['hidden'] == undefined ? true : !item['hidden'];
        })
        $('#btn_open_column_list form').eq(0).form('load', formData);
        $('#btn_open_column_list form .easyui-checkbox').each(function () {
            //  绑定事件
            $(this).checkbox({
                onChange: function (checked) {
                    let opts = $(this).checkbox('options');
                    if (checked) {
                        $(kendoGridID).data('kendoGrid').showColumn(opts.name);
                    } else {
                        $(kendoGridID).data('kendoGrid').hideColumn(opts.name);
                    }
                }
            })
        })
    } else {
        $('#btn_open_column_list').dialog('open');
    }
}

function btn_export_excel() {
    switch (getCurrentIndex()) {
        case 0:
            $('#v_grid_3').data('kendoGrid').saveAsExcel();
            break;
        case 1:
            $('#v_grid_4').data('kendoGrid').saveAsExcel();
            break;
    }
}

function btn_close() {
    window.parent.closeTab();
}